<?php

namespace App\Http\Controllers\Admin;

use App\Models\Member as MemberInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class Member extends Controller
{
    //会员列表
    public function all ()
    {
        $members = (new MemberInfo)->orderBy('created_at')->paginate(10);
        $data = [
            'members' => $members,
        ];
        return view('admin.member.list',$data);
    }

    //会员添加
    public function add ()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['username','password','nickname','email']);
            $result = (new MemberInfo)->add($data);
            if($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => "添加成功",
                    'url' => url('admin/memberlist')
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            return $msg; 
        }
        return view('admin.member.add');
    }

    //会员编辑
    public function edit ()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['id','username','password','nickname','email']);
            $result = (new MemberInfo)->edit($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => "编辑成功",
                    'url' => url('admin/memberlist')
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            return $msg;
        }

        $id = request()->route('id');
        $members = MemberInfo::find($id);
        $data = [
            'members' => $members,
        ];
        return view('admin.member.edit',$data);
    }

    //会员删除
    public function del ()
    {
        $members = (new MemberInfo)->find(request('id'));
        $result = $members->delete();
        if ($result) {
            $msg = [
                'code' => 1,
                'msg' => "删除成功",
                'url' => url('admin/memberlist'),
            ];
        } else {
            $msg = [
                'code' => 0,
                'msg' => "删除失败"
            ];
        }
        return $msg;
    }
}
